<template>
  <div class="downstream-management">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-row">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="24" color="#409EFF">
                <Connection />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.totalChannels }}</div>
              <div class="stat-label">总渠道数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="24" color="#67C23A">
                <CircleCheck />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.connectedChannels }}</div>
              <div class="stat-label">已连接</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="24" color="#E6A23C">
                <TrendCharts />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.avgSuccessRate }}%</div>
              <div class="stat-label">平均成功率</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="24" color="#F56C6C">
                <DataAnalysis />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.todayPushCount }}</div>
              <div class="stat-label">今日推送</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-card>
      <template #header>
        <div class="card-header">
          <span>下游渠道管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd">新增渠道</el-button>
            <el-button @click="handleExport">导出渠道</el-button>
            <el-button @click="handleImport">导入渠道</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="渠道名称">
              <el-input v-model="searchForm.channelName" placeholder="请输入渠道名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="渠道类型">
              <el-select v-model="searchForm.channelType" placeholder="请选择渠道类型" clearable style="width: 100%">
                <el-option label="银行" value="bank" />
                <el-option label="消费金融" value="consumer_finance" />
                <el-option label="小贷公司" value="small_loan" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 100%">
                <el-option label="启用" value="enabled" />
                <el-option label="禁用" value="disabled" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="连接状态">
              <el-select v-model="searchForm.connectionStatus" placeholder="请选择连接状态" clearable style="width: 100%">
                <el-option label="正常" value="connected" />
                <el-option label="断开" value="disconnected" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="6">
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 批量操作 -->
      <div class="batch-actions">
        <el-button 
          type="danger" 
          @click="handleBatchDelete"
          :disabled="selectedRows.length === 0"
          :loading="batchDeleteLoading"
        >
          批量删除
        </el-button>
        <el-button 
          @click="handleBatchStatus('enabled')"
          :disabled="selectedRows.length === 0"
          :loading="batchStatusLoading"
        >
          批量启用
        </el-button>
        <el-button 
          @click="handleBatchStatus('disabled')"
          :disabled="selectedRows.length === 0"
          :loading="batchStatusLoading"
        >
          批量禁用
        </el-button>
        <el-button 
          @click="handleBatchTest"
          :disabled="selectedRows.length === 0"
          :loading="batchTestLoading"
        >
          批量测试
        </el-button>
      </div>

      <!-- 渠道表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :max-height="tableHeight"
        class="responsive-table"
      >
        <el-table-column type="selection" width="55" fixed="left" />
        <el-table-column prop="channelName" label="渠道名称" min-width="150" />
        <el-table-column prop="channelType" label="渠道类型" width="120">
          <template #default="{ row }">
            <el-tag>{{ getChannelTypeLabel(row.channelType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="apiEndpoint" label="API地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="webhookUrl" label="推送地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="pushMode" label="推送模式" width="100">
          <template #default="{ row }">
            <el-tag :type="row.pushMode === 'realtime' ? 'success' : 'warning'">
              {{ getPushModeLabel(row.pushMode) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="connectionStatus" label="连接状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.connectionStatus === 'connected' ? 'success' : 'danger'">
              {{ getConnectionStatusLabel(row.connectionStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="enabled"
              inactive-value="disabled"
              @change="handleStatusChange(row)"
              :loading="statusLoadingMap[row.id]"
            />
          </template>
        </el-table-column>
        <el-table-column prop="successRate" label="成功率" width="80">
          <template #default="{ row }">
            <span :class="getSuccessRateClass(row.successRate)">
              {{ row.successRate }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="todayPushCount" label="今日推送" width="100" />
        <el-table-column prop="todaySuccessCount" label="今日成功" width="100" />
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleView(row)">查看</el-button>
            <el-button type="text" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" @click="handleTest(row)" :loading="testLoadingMap[row.id]">测试</el-button>
            <el-button type="text" @click="handleFieldMapping(row)">字段映射</el-button>
            <el-button type="text" @click="handlePushConfig(row)">推送配置</el-button>
            <el-button type="text" @click="handleDelete(row)" style="color: #f56c6c">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination responsive-pagination"
      />
    </el-card>

    <!-- 效果统计图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :md="12">
        <el-card>
          <template #header>
            <span>渠道成功率排行</span>
          </template>
          <div ref="successRateChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-card>
          <template #header>
            <span>渠道推送量趋势</span>
          </template>
          <div ref="pushTrendChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 渠道详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      title="渠道详情"
      width="700px"
      class="responsive-dialog"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="渠道名称">{{ detailDialog.data.channelName }}</el-descriptions-item>
        <el-descriptions-item label="渠道类型">
          <el-tag>{{ getChannelTypeLabel(detailDialog.data.channelType) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="API地址">{{ detailDialog.data.apiEndpoint }}</el-descriptions-item>
        <el-descriptions-item label="推送地址">{{ detailDialog.data.webhookUrl }}</el-descriptions-item>
        <el-descriptions-item label="推送模式">
          <el-tag :type="detailDialog.data.pushMode === 'realtime' ? 'success' : 'warning'">
            {{ getPushModeLabel(detailDialog.data.pushMode) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="连接状态">
          <el-tag :type="detailDialog.data.connectionStatus === 'connected' ? 'success' : 'danger'">
            {{ getConnectionStatusLabel(detailDialog.data.connectionStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detailDialog.data.status === 'enabled' ? 'success' : 'danger'">
            {{ detailDialog.data.status === 'enabled' ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="成功率">
          <span :class="getSuccessRateClass(detailDialog.data.successRate)">
            {{ detailDialog.data.successRate }}%
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="今日推送">{{ detailDialog.data.todayPushCount }}</el-descriptions-item>
        <el-descriptions-item label="今日成功">{{ detailDialog.data.todaySuccessCount }}</el-descriptions-item>
        <el-descriptions-item label="API密钥" :span="2">{{ detailDialog.data.apiKey || '无' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailDialog.data.remark || '无' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailDialog.data.createdTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailDialog.data.updatedTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑渠道对话框 -->
    <el-dialog
      v-model="formDialog.visible"
      :title="formDialog.title"
      width="600px"
      class="responsive-dialog"
    >
      <el-form ref="channelFormRef" :model="formDialog.form" :rules="formRules" label-width="100px">
        <el-form-item label="渠道名称" prop="channelName">
          <el-input v-model="formDialog.form.channelName" placeholder="请输入渠道名称" />
        </el-form-item>
        <el-form-item label="渠道类型" prop="channelType">
          <el-select v-model="formDialog.form.channelType" placeholder="请选择渠道类型" style="width: 100%">
            <el-option label="银行" value="bank" />
            <el-option label="消费金融" value="consumer_finance" />
            <el-option label="小贷公司" value="small_loan" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="API地址" prop="apiEndpoint">
          <el-input v-model="formDialog.form.apiEndpoint" placeholder="请输入API地址" />
        </el-form-item>
        <el-form-item label="推送地址" prop="webhookUrl">
          <el-input v-model="formDialog.form.webhookUrl" placeholder="请输入推送地址" />
        </el-form-item>
        <el-form-item label="推送模式" prop="pushMode">
          <el-radio-group v-model="formDialog.form.pushMode">
            <el-radio label="realtime">实时推送</el-radio>
            <el-radio label="batch">批量推送</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="API密钥" prop="apiKey">
          <el-input v-model="formDialog.form.apiKey" placeholder="请输入API密钥" show-password />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formDialog.form.status">
            <el-radio label="enabled">启用</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formDialog.form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="formDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 字段映射对话框 -->
    <el-dialog
      v-model="fieldMappingDialog.visible"
      title="字段映射配置"
      width="800px"
      class="responsive-dialog"
    >
      <div class="field-mapping-container">
        <div class="mapping-header">
          <h4>字段映射关系</h4>
          <el-button type="primary" size="small" @click="addMapping">添加映射</el-button>
        </div>
        <el-table :data="fieldMappingDialog.mappings" border style="width: 100%" class="mapping-table">
          <el-table-column prop="sourceField" label="源字段" width="200">
            <template #default="{ row }">
              <el-input v-model="row.sourceField" placeholder="请输入源字段" />
            </template>
          </el-table-column>
          <el-table-column prop="targetField" label="目标字段" width="200">
            <template #default="{ row }">
              <el-input v-model="row.targetField" placeholder="请输入目标字段" />
            </template>
          </el-table-column>
          <el-table-column prop="fieldType" label="字段类型" width="150">
            <template #default="{ row }">
              <el-select v-model="row.fieldType" placeholder="请选择字段类型" style="width: 100%">
                <el-option label="字符串" value="string" />
                <el-option label="数字" value="number" />
                <el-option label="日期" value="date" />
                <el-option label="布尔值" value="boolean" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="isRequired" label="是否必填" width="100">
            <template #default="{ row }">
              <el-checkbox v-model="row.isRequired" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ $index }">
              <el-button type="text" @click="removeMapping($index)" style="color: #f56c6c">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="fieldMappingDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleFieldMappingSubmit" :loading="mappingLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 数据推送配置对话框 -->
    <el-dialog
      v-model="pushConfigDialog.visible"
      title="数据推送配置"
      width="700px"
      class="responsive-dialog"
    >
      <el-form :model="pushConfigDialog.form" label-width="120px">
        <el-form-item label="推送策略">
          <el-radio-group v-model="pushConfigDialog.form.pushStrategy">
            <el-radio label="immediate">立即推送</el-radio>
            <el-radio label="scheduled">定时推送</el-radio>
            <el-radio label="conditional">条件推送</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="推送频率" v-if="pushConfigDialog.form.pushStrategy === 'scheduled'">
          <el-select v-model="pushConfigDialog.form.pushFrequency" placeholder="请选择推送频率" style="width: 100%">
            <el-option label="每小时" value="hourly" />
            <el-option label="每6小时" value="6hourly" />
            <el-option label="每天" value="daily" />
            <el-option label="每周" value="weekly" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="推送条件" v-if="pushConfigDialog.form.pushStrategy === 'conditional'">
          <el-input
            v-model="pushConfigDialog.form.pushCondition"
            type="textarea"
            :rows="3"
            placeholder="请输入推送条件，例如：data.status == 'qualified'"
          />
        </el-form-item>
        
        <el-form-item label="批次大小">
          <el-input-number
            v-model="pushConfigDialog.form.batchSize"
            :min="1"
            :max="1000"
            :step="10"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="重试次数">
              <el-input-number
                v-model="pushConfigDialog.form.retryCount"
                :min="0"
                :max="10"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重试间隔(秒)">
              <el-input-number
                v-model="pushConfigDialog.form.retryInterval"
                :min="1"
                :max="300"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="超时时间(秒)">
          <el-input-number
            v-model="pushConfigDialog.form.timeout"
            :min="5"
            :max="300"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="数据格式">
          <el-radio-group v-model="pushConfigDialog.form.dataFormat">
            <el-radio label="json">JSON</el-radio>
            <el-radio label="xml">XML</el-radio>
            <el-radio label="csv">CSV</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="数据压缩">
          <el-radio-group v-model="pushConfigDialog.form.compression">
            <el-radio label="none">不压缩</el-radio>
            <el-radio label="gzip">GZIP</el-radio>
            <el-radio label="zip">ZIP</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="失败处理">
          <el-radio-group v-model="pushConfigDialog.form.failureHandling">
            <el-radio label="discard">丢弃</el-radio>
            <el-radio label="queue">队列重试</el-radio>
            <el-radio label="manual">人工处理</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="启用状态">
          <el-switch
            v-model="pushConfigDialog.form.enabled"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="pushConfigDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handlePushConfigSubmit" :loading="pushConfigLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

// 导入功能
const handleImport = () => {
  ElMessage.info('导入功能开发中')
}
+ 
+ // 推送配置
+ const handlePushConfig = (row: any) => {
+   pushConfigDialog.channelId = row.id
+   // 获取当前推送配置
+   const currentConfig = row.pushConfig || {}
+   pushConfigDialog.form = {
+     pushStrategy: currentConfig.pushStrategy || 'immediate',
+     pushFrequency: currentConfig.pushFrequency || 'hourly',
+     pushCondition: currentConfig.pushCondition || '',
+     batchSize: currentConfig.batchSize || 100,
+     retryCount: currentConfig.retryCount || 3,
+     retryInterval: currentConfig.retryInterval || 30,
+     timeout: currentConfig.timeout || 30,
+     dataFormat: currentConfig.dataFormat || 'json',
+     compression: currentConfig.compression || 'none',
+     failureHandling: currentConfig.failureHandling || 'queue',
+     enabled: currentConfig.enabled !== false
+   }
+   pushConfigDialog.visible = true
+ }
+ 
+ // 提交推送配置
+ const handlePushConfigSubmit = async () => {
+   if (!pushConfigDialog.channelId) return
+   
+   pushConfigLoading.value = true
+   try {
+     // 验证配置
+     if (pushConfigDialog.form.pushStrategy === 'conditional' && !pushConfigDialog.form.pushCondition.trim()) {
+       ElMessage.error('请输入推送条件')
+       return
+     }
+     
+     if (pushConfigDialog.form.pushStrategy === 'scheduled' && !pushConfigDialog.form.pushFrequency) {
+       ElMessage.error('请选择推送频率')
+       return
+     }
+     
+     // 调用API更新推送配置
+     await updateDownstreamChannel(pushConfigDialog.channelId, {
+       pushConfig: pushConfigDialog.form
+     })
+     
+     ElMessage.success('推送配置更新成功')
+     pushConfigDialog.visible = false
+     fetchData()
+   } catch (error) {
+     ElMessage.error('推送配置更新失败')
+   } finally {
+     pushConfigLoading.value = false
+   }
+ }

<style scoped>
.downstream-management {
  padding: 20px;
}

/* 统计卡片样式 */
.statistics-row {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  margin-right: 20px;
  padding: 12px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

/* 图表样式 */
.chart-row {
  margin-top: 20px;
}

.chart-container {
  width: 100%;
  height: 350px;
  background: #fff;
  border-radius: 4px;
}

/* 原有的样式保持不变 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.batch-actions {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.text-success {
  color: #67c23a;
}

.text-warning {
  color: #e6a23c;
}

.text-danger {
  color: #f56c6c;
}

.field-mapping-container {
  padding: 20px;
}

.mapping-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.mapping-header h4 {
  margin: 0;
  color: #303133;
}

.mapping-table {
  margin-top: 10px;
}

.mapping-table .el-input,
.mapping-table .el-select {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .downstream-management {
    padding: 10px;
  }
  
  .stat-content {
    padding: 15px;
  }
  
  .stat-value {
    font-size: 24px;
  }
  
  .chart-container {
    height: 300px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .batch-actions {
    flex-wrap: wrap;
  }
  
  .responsive-table {
    font-size: 12px;
  }
  
  .responsive-pagination {
    flex-wrap: wrap;
  }
  
  .responsive-dialog {
    width: 95% !important;
  }
}

@media (max-width: 480px) {
  .stat-content {
    flex-direction: column;
    text-align: center;
  }
  
  .stat-icon {
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .mapping-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import { 
  getDownstreamChannels, 
  createDownstreamChannel, 
  updateDownstreamChannel, 
  deleteDownstreamChannel,
  batchUpdateDownstreamChannel,
  exportDownstreamChannels,
  testDownstreamChannel
} from '@/api/channel'
import type { DownstreamChannel, DownstreamChannelForm } from '@/api/channel'

// 响应式数据
const loading = ref(false)
const tableData = ref<DownstreamChannel[]>([])
const selectedRows = ref<DownstreamChannel[]>([])
const tableHeight = ref(400)

// 统计信息
const statistics = reactive({
  totalChannels: 0,
  connectedChannels: 0,
  avgSuccessRate: 0,
  todayPushCount: 0
})

// 搜索表单
const searchForm = reactive({
  channelName: '',
  channelType: '',
  status: '',
  connectionStatus: ''
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 批量操作loading状态
const batchDeleteLoading = ref(false)
const batchStatusLoading = ref(false)
const batchTestLoading = ref(false)
const statusLoadingMap = ref<Record<string, boolean>>({})

// 对话框配置
const detailDialog = reactive({
  visible: false,
  data: {} as DownstreamChannel
})

const formDialog = reactive({
  visible: false,
  title: '新增渠道',
  form: {} as DownstreamChannelForm
})

// 推送配置对话框
const pushConfigDialog = reactive({
  visible: false,
  channelId: '',
  form: {
    pushStrategy: 'immediate',
    pushFrequency: 'hourly',
    pushCondition: '',
    batchSize: 100,
    retryCount: 3,
    retryInterval: 30,
    timeout: 30,
    dataFormat: 'json',
    compression: 'none',
    failureHandling: 'queue',
    enabled: true
  }
})

const pushConfigLoading = ref(false)

// 字段映射对话框
const fieldMappingDialog = reactive({
  visible: false,
  channelId: '',
  mappings: [] as Array<{
    sourceField: string
    targetField: string
    fieldType: string
    isRequired: boolean
  }>
})

// 字段映射加载状态
const mappingLoading = ref(false)

// 图表实例
const successRateChart = ref<HTMLElement>()
const pushTrendChart = ref<HTMLElement>()
let successRateChartInstance: echarts.ECharts | null = null
let pushTrendChartInstance: echarts.ECharts | null = null

// 表单验证规则
const formRules = {
  channelName: [{ required: true, message: '请输入渠道名称', trigger: 'blur' }],
  channelType: [{ required: true, message: '请选择渠道类型', trigger: 'change' }],
  apiEndpoint: [{ required: true, message: '请输入API地址', trigger: 'blur' }],
  webhookUrl: [{ required: true, message: '请输入推送地址', trigger: 'blur' }],
  pushMode: [{ required: true, message: '请选择推送模式', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 获取表格数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const { data } = await getDownstreamChannels(params)
    tableData.value = data.list
    pagination.total = data.total
    
    // 更新统计信息
    updateStatistics(data.list)
    
    // 初始化图表
    nextTick(() => {
      initCharts()
    })
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 更新统计信息
const updateStatistics = (data: DownstreamChannel[]) => {
  statistics.totalChannels = data.length
  statistics.connectedChannels = data.filter(item => item.connectionStatus === 'connected').length
  
  const successRates = data.map(item => item.successRate || 0)
  statistics.avgSuccessRate = successRates.length > 0 
    ? Math.round(successRates.reduce((sum, rate) => sum + rate, 0) / successRates.length)
    : 0
    
  statistics.todayPushCount = data.reduce((sum, item) => sum + (item.todayPushCount || 0), 0)
}

// 初始化图表
const initCharts = () => {
  initSuccessRateChart()
  initPushTrendChart()
}

// 初始化成功率排行图表
const initSuccessRateChart = () => {
  if (!successRateChart.value) return
  
  if (successRateChartInstance) {
    successRateChartInstance.dispose()
  }
  
  successRateChartInstance = echarts.init(successRateChart.value)
  
  const sortedData = [...tableData.value]
    .sort((a, b) => (b.successRate || 0) - (a.successRate || 0))
    .slice(0, 10)
  
  const option = {
    title: {
      text: '渠道成功率排行',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      min: 0,
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    yAxis: {
      type: 'category',
      data: sortedData.map(item => item.channelName)
    },
    series: [{
      name: '成功率',
      type: 'bar',
      data: sortedData.map(item => item.successRate || 0),
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
          { offset: 0, color: '#83bff6' },
          { offset: 0.5, color: '#188df0' },
          { offset: 1, color: '#188df0' }
        ])
      },
      label: {
        show: true,
        position: 'right',
        formatter: '{c}%'
      }
    }]
  }
  
  successRateChartInstance.setOption(option)
}

// 初始化推送量趋势图表
const initPushTrendChart = () => {
  if (!pushTrendChart.value) return
  
  if (pushTrendChartInstance) {
    pushTrendChartInstance.dispose()
  }
  
  pushTrendChartInstance = echarts.init(pushTrendChart.value)
  
  // 模拟7天的推送数据
  const dates = []
  const pushCounts = []
  const successCounts = []
  
  for (let i = 6; i >= 0; i--) {
    const date = new Date()
    date.setDate(date.getDate() - i)
    dates.push(date.toLocaleDateString())
    
    // 模拟数据
    pushCounts.push(Math.floor(Math.random() * 1000) + 500)
    successCounts.push(Math.floor(Math.random() * 800) + 400)
  }
  
  const option = {
    title: {
      text: '推送量趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['推送量', '成功量'],
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '推送量',
        type: 'line',
        data: pushCounts,
        smooth: true,
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          opacity: 0.3
        }
      },
      {
        name: '成功量',
        type: 'line',
        data: successCounts,
        smooth: true,
        itemStyle: {
          color: '#67C23A'
        },
        areaStyle: {
          opacity: 0.3
        }
      }
    ]
  }
  
  pushTrendChartInstance.setOption(option)
}

// 搜索和重置
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

const handleReset = () => {
  searchForm.channelName = ''
  searchForm.channelType = ''
  searchForm.status = ''
  searchForm.connectionStatus = ''
  handleSearch()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchData()
}

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchData()
}

// 表格选择
const handleSelectionChange = (rows: DownstreamChannel[]) => {
  selectedRows.value = rows
}

// 状态切换
const handleStatusChange = async (row: DownstreamChannel) => {
  statusLoadingMap.value[row.id] = true
  try {
    await updateDownstreamChannel(row.id, { status: row.status })
    ElMessage.success('状态更新成功')
  } catch (error) {
    ElMessage.error('状态更新失败')
    // 恢复状态
    row.status = row.status === 'enabled' ? 'disabled' : 'enabled'
  } finally {
    statusLoadingMap.value[row.id] = false
  }
}

// 新增渠道
const handleAdd = () => {
  formDialog.title = '新增渠道'
  formDialog.form = {
    channelName: '',
    channelType: '',
    apiEndpoint: '',
    webhookUrl: '',
    pushMode: 'realtime',
    apiKey: '',
    status: 'enabled',
    remark: ''
  }
  formDialog.visible = true
}

// 编辑渠道
const handleEdit = (row: DownstreamChannel) => {
  formDialog.title = '编辑渠道'
  formDialog.form = { ...row }
  formDialog.visible = true
}

// 查看详情
const handleDetail = (row: DownstreamChannel) => {
  detailDialog.data = row
  detailDialog.visible = true
}

// 测试连接
const handleTest = async (row: DownstreamChannel) => {
  try {
    const result = await testDownstreamChannel(row.id)
    if (result.success) {
      ElMessage.success('连接测试成功')
    } else {
      ElMessage.error('连接测试失败: ' + result.message)
    }
  } catch (error) {
    ElMessage.error('连接测试失败')
  }
}

// 删除渠道
const handleDelete = async (row: DownstreamChannel) => {
  try {
    await ElMessageBox.confirm('确定要删除该渠道吗？', '提示', {
      type: 'warning'
    })
    
    await deleteDownstreamChannel(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量操作
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的渠道')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个渠道吗？`, '提示', {
      type: 'warning'
    })
    
    batchDeleteLoading.value = true
    const ids = selectedRows.value.map(row => row.id)
    await batchUpdateDownstreamChannel({ ids, action: 'delete' })
    ElMessage.success('批量删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  } finally {
    batchDeleteLoading.value = false
  }
}

const handleBatchStatus = async (status: 'enabled' | 'disabled') => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要操作的渠道')
    return
  }
  
  try {
    batchStatusLoading.value = true
    const ids = selectedRows.value.map(row => row.id)
    await batchUpdateDownstreamChannel({ ids, action: 'status', status })
    ElMessage.success(`批量${status === 'enabled' ? '启用' : '禁用'}成功`)
    fetchData()
  } catch (error) {
    ElMessage.error(`批量${status === 'enabled' ? '启用' : '禁用'}失败`)
  } finally {
    batchStatusLoading.value = false
  }
}

const handleBatchTest = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要测试的渠道')
    return
  }
  
  batchTestLoading.value = true
  let successCount = 0
  let failCount = 0
  
  for (const row of selectedRows.value) {
    try {
      const result = await testDownstreamChannel(row.id)
      if (result.success) {
        successCount++
      } else {
        failCount++
      }
    } catch (error) {
      failCount++
    }
  }
  
  batchTestLoading.value = false
  ElMessage.success(`批量测试完成，成功: ${successCount}，失败: ${failCount}`)
}

// 字段映射配置
const handleFieldMapping = (row: DownstreamChannel) => {
  fieldMappingDialog.channelId = row.id
  fieldMappingDialog.mappings = row.fieldMappings || []
  fieldMappingDialog.visible = true
}

// 保存字段映射
const handleFieldMappingSubmit = async () => {
  if (!fieldMappingDialog.channelId) return
  
  mappingLoading.value = true
  try {
    await updateDownstreamChannel(fieldMappingDialog.channelId, {
      fieldMappings: fieldMappingDialog.mappings
    })
    ElMessage.success('字段映射保存成功')
    fieldMappingDialog.visible = false
    fetchData()
  } catch (error) {
    ElMessage.error('字段映射保存失败')
  } finally {
    mappingLoading.value = false
  }
}

// 添加字段映射
const addMapping = () => {
  fieldMappingDialog.mappings.push({
    sourceField: '',
    targetField: '',
    fieldType: 'string',
    isRequired: false
  })
}

// 删除字段映射
const removeMapping = (index: number) => {
  fieldMappingDialog.mappings.splice(index, 1)
}

// 删除字段映射
const removeFieldMapping = (index: number) => {
  fieldMappingDialog.mappings.splice(index, 1)
}

// 推送配置
const handlePushConfig = (row: any) => {
  pushConfigDialog.channelId = row.id
  // 获取当前推送配置
  const currentConfig = row.pushConfig || {}
  pushConfigDialog.form = {
    pushStrategy: currentConfig.pushStrategy || 'immediate',
    pushFrequency: currentConfig.pushFrequency || 'hourly',
    pushCondition: currentConfig.pushCondition || '',
    batchSize: currentConfig.batchSize || 100,
    retryCount: currentConfig.retryCount || 3,
    retryInterval: currentConfig.retryInterval || 30,
    timeout: currentConfig.timeout || 30,
    dataFormat: currentConfig.dataFormat || 'json',
    compression: currentConfig.compression || 'none',
    failureHandling: currentConfig.failureHandling || 'queue',
    enabled: currentConfig.enabled !== false
  }
  pushConfigDialog.visible = true
}

// 提交推送配置
const handlePushConfigSubmit = async () => {
  if (!pushConfigDialog.channelId) return
  
  pushConfigLoading.value = true
  try {
    // 验证配置
    if (pushConfigDialog.form.pushStrategy === 'conditional' && !pushConfigDialog.form.pushCondition.trim()) {
      ElMessage.error('请输入推送条件')
      return
    }
    
    if (pushConfigDialog.form.pushStrategy === 'scheduled' && !pushConfigDialog.form.pushFrequency) {
      ElMessage.error('请选择推送频率')
      return
    }
    
    // 调用API更新推送配置
    await updateDownstreamChannel(pushConfigDialog.channelId, {
      pushConfig: pushConfigDialog.form
    })
    
    ElMessage.success('推送配置更新成功')
    pushConfigDialog.visible = false
    fetchData()
  } catch (error) {
    ElMessage.error('推送配置更新失败')
  } finally {
    pushConfigLoading.value = false
  }
}

// 导入功能
const handleImport = () => {
  ElMessage.info('导入功能开发中')
}

// 导出功能
const handleExport = async () => {
  try {
    const blob = await exportDownstreamChannels(searchForm)
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `下游渠道_${new Date().toLocaleDateString()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 表单提交
const handleSubmit = async () => {
  try {
    const formData = { ...formDialog.form }
    
    if (formDialog.title === '新增渠道') {
      await createDownstreamChannel(formData)
      ElMessage.success('新增成功')
    } else {
      await updateDownstreamChannel(formData.id, formData)
      ElMessage.success('更新成功')
    }
    
    formDialog.visible = false
    fetchData()
  } catch (error) {
    ElMessage.error(formDialog.title === '新增渠道' ? '新增失败' : '更新失败')
  }
}

// 工具函数
const getChannelTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    bank: '银行',
    consumer_finance: '消费金融',
    small_loan: '小贷公司',
    other: '其他'
  }
  return labels[type] || type
}

const getPushModeLabel = (mode: string) => {
  const labels: Record<string, string> = {
    realtime: '实时推送',
    batch: '批量推送'
  }
  return labels[mode] || mode
}

const getConnectionStatusLabel = (status: string) => {
  const labels: Record<string, string> = {
    connected: '已连接',
    disconnected: '未连接'
  }
  return labels[status] || status
}

const getSuccessRateClass = (rate: number) => {
  if (rate >= 90) return 'text-success'
  if (rate >= 70) return 'text-warning'
  return 'text-danger'
}

// 窗口大小改变时重新调整图表
const handleResize = () => {
  if (successRateChartInstance) {
    successRateChartInstance.resize()
  }
  if (pushTrendChartInstance) {
    pushTrendChartInstance.resize()
  }
}

// 生命周期
onMounted(() => {
  fetchData()
  window.addEventListener('resize', handleResize)
})

// 清理
const cleanup = () => {
  if (successRateChartInstance) {
    successRateChartInstance.dispose()
  }
  if (pushTrendChartInstance) {
    pushTrendChartInstance.dispose()
  }
  window.removeEventListener('resize', handleResize)
}

// 暴露函数给模板使用
declare global {
  interface Window {
    cleanup: () => void
  }
}

window.cleanup = cleanup
</script>